package com.cby.operation.pay.ui

import android.app.Activity
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.text.TextUtils
import android.view.View
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.ListView
import android.widget.TextView
import com.cby.operation.common.ext.getId
import com.cby.operation.common.ext.showToast
import com.cby.operation.common.ui.BaseDialogFragment
import com.cby.operation.common.util.AppUtils
import com.cby.operation.common.util.CbyLogUtils.i
import com.cby.operation.common.util.FastClickUtils
import com.cby.operation.common.util.HandlerUtils
import com.cby.operation.common.util.NetworkUtils
import com.cby.operation.login.LoginManager
import com.cby.operation.login.UserInfo
import com.cby.operation.login.data.InternalUser
import com.cby.operation.pay.PayManager
import com.cby.operation.pay.bean.*
import com.cby.operation.pay.channel.PayResultCallBack
import com.cby.operation.pay.channel.PayWrapper
import com.cby.operation.pay.channel.alipay.AlipayWrapper
import com.cby.operation.pay.channel.wechat.WechatPayWrapper
import com.cby.operation.pay.core.PayEngine
import com.cby.operation.pay.data.PayApiRepository
import com.cby.operation.pay.data.PayApiRepository.OnOrderQueryCallBack
import com.cby.operation.pay.data.PayApiRepository.orderQuery
import com.cby.operation.pay.data.PayLogApiRepository.payReport
import com.cby.operation.sdk.*
import java.util.*

/**
 * Description:该对话框是用来显示支付的结果
 *
 * @author 陈宝阳
 * @create 2020/8/6 10:10
 */
class PayDialogFragment : BaseDialogFragment(), PayEngine.CallBack {

    private lateinit var payCloseIv: ImageView
    private lateinit var goodsNameTv: TextView
    private lateinit var payMoneyTv: TextView

    /**
     * 这部分是支付方式的选择的相关控件
     */
    private lateinit var payChannelsLl: LinearLayout
    private lateinit var payChannelsLv: ListView
    private lateinit var payBtn: TextView

    /**
     * 这部分是打开支付方式的加载效果相关控件
     */
    private lateinit var openLoadingLl: LinearLayout
    private lateinit var openDescTv: TextView

    private var adapter: PayChannelsAdapter? = null
    private var payInfo: PayInfo? = null
    private var payConfig: PayConfig? = null

    override fun parseArgs() {
        payInfo = arguments.getParcelable(KEY_PAY_INFO)
        payConfig = arguments.getParcelable(KEY_PAY_CONFIG)
    }

    override fun initView(view: View?) {
        view?.let {
            payCloseIv = it.findViewById(getId("iv_pay_close"))
            goodsNameTv = it.findViewById(getId("tv_goods_name"))
            payMoneyTv = it.findViewById(getId("tv_pay_money"))
            payChannelsLl = it.findViewById(getId("ll_pay_channels"))
            payChannelsLv = it.findViewById(getId("lv_pay_channels"))
            payBtn = it.findViewById(getId("tv_pay_btn"))
            openLoadingLl = it.findViewById(getId("ll_open_loading"))
            openDescTv = it.findViewById(getId("tv_open_desc"))
            openLoadingLl.visibility = View.GONE
        }

    }

    override fun setContent() {
        if (payInfo != null) {
            goodsNameTv.text = payInfo!!.goodsName
            payMoneyTv.text = "¥ ${payInfo!!.money}"
            adapter = PayChannelsAdapter(activity, payChannels)
            payChannelsLv.adapter = adapter
        }
    }

    //设置默认选择第一项支付方式
    private val payChannels: MutableList<PayChannel>
        get() {
            val channels: MutableList<PayChannel> = mutableListOf()
            if (payConfig != null && payConfig!!.payChannels != null) {
                for (i in payConfig!!.payChannels!!.indices) {
                    val channelValue = payConfig!!.payChannels!![i]
                    var payChannel: PayChannel? = null
                    when (channelValue) {
                        VALUE_PAY_CHANNEL_WECHAT_H5 -> {
                            payChannel = PayChannel(
                                "hykb_icon_pay_channel_wechat",
                                STRING_PAY_CHANNEL_WECHAT, channelValue
                            )
                            channels.add(payChannel)
                        }
                        VALUE_PAY_CHANNEL_ALIPAY -> {
                            payChannel = PayChannel(
                                "hykb_icon_pay_channel_alipay",
                                STRING_PAY_CHANNEL_ALIPAY, channelValue
                            )
                            channels.add(payChannel)
                        }
                    }
                }

                //设置默认选择第一项支付方式
                if (channels.size > 0) {
                    channels[0].select = true
                }
            }
            return channels
        }

    override fun initListener() {
        payBtn.setOnClickListener(View.OnClickListener {
            val payChannel: PayChannel? = adapter!!.selectPayChannel
            //判断是不是选择了微信支付方式，如果是，检测是否有安装微信
            if (!AppUtils.isWeChatAvailable(activity)
                && payChannel != null
                && TextUtils.equals(payChannel.payChannelValue, VALUE_PAY_CHANNEL_WECHAT_H5
                )
            ) {
                activity.showToast("您尚未安装微信，请先安装或选择其他支付方式")
                return@OnClickListener
            }
            if (FastClickUtils.isFastDoubleClick) {
                return@OnClickListener
            }
            if (!NetworkUtils.isConnected(activity)) {
                activity.showToast(ERR_MSG_NETWORK_ERROR)
                return@OnClickListener
            }

            //显示是打开某个支付方式的加载
            payChannelsLl.visibility = View.GONE
            openLoadingLl.visibility = View.VISIBLE
            if (payChannel != null) {
                openDescTv.text = "正在打开${payChannel.payChannelName}"
                PayManager.instance.engine.submitOrder(payChannel, this@PayDialogFragment)
            }
        })

        payCloseIv.setOnClickListener {
            val result = PayResult()
            result.payInfo = payInfo
            result.resultCode = CODE_PAY_DIALOG_CLOSE
            result.message = ERR_MSG_PAY_DIALOG_CLOSE
            PayManager.instance.handlePayCallBack(result)
            dismiss()
        }
    }

    override fun onResume() {
        super.onResume()
        i(TAG, "onResume")
        PayManager.instance.engine.checkOrder()
    }


    override fun onResult(status: String?, resultInfo: String?) {
        openDescTv.text = resultInfo
    }

    override fun layoutName(): String {
        return "pay_dialog_fragment"
    }

    companion object {
        private const val TAG = "m3839"

        fun show(activity: Activity, payInfo: PayInfo?, payConfig: PayConfig?): PayDialogFragment {
            val fragment = PayDialogFragment()
            val data = Bundle()
            data.putParcelable(KEY_PAY_CONFIG, payConfig)
            data.putParcelable(KEY_PAY_INFO, payInfo)
            fragment.arguments = data
            fragment.show(activity.fragmentManager, TAG_FRAGMENT_PAY_SUBMIT)
            return fragment
        }
    }

}